<?php
namespace plugins\community\controller;

use cmf\controller\ApiPluginBaseController;
use think\Db;
use think\Exception;
use think\Request;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("社区接口文档")
 * @Apidoc\Group("community")
 */
class ApiIndexController extends ApiPluginBaseController
{
    private  $pageNum = "20";

    /**
     * 发布社区动态
     */
    public function publicCommunity(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $add['userid'] = $param['userid'];
        $add['addtime'] = time();
        if(!empty($param['catid'])){
            $add['catid'] = $param['catid'];
        }
        if(!empty($param['content'])){
            $add['content'] = $param['content'];
        }
        if(!empty($param['img'])){
            $add['img'] = implode(",", $param['img']);
        }
        if(!empty($param['lng'])){
            $add['lng'] = $param['lng'];
        }
        if(!empty($param['lat'])){
            $add['lat'] = $param['lat'];
        }
        if(!empty($param['lng']) && !empty($param['lat'])){
            $add['city'] = $this->getCityName($param['lat'],$param['lng']);
        }
        $return = db('community')->insert($add);
        if ($return) {
            return api_json_echo(true, '发布成功！', null, 200);
        } else {
            return api_json_echo(false, '发布失败！', null, 101);
        }
    }

    /**
     * 社区动态分类
     */
    public function categoryList(){
        $list = db('community_category')->order('sort')->select()->each(function ($item){
            return $item;
        });
        return api_json_echo( true , '获取成功' , $list , 200);
    }

    /*
     *参数说明：
     *$lng  经度
     *$lat   纬度
     *$distance  周边半径  默认是500米（0.5Km）
     */
    public function returnSquarePoint($lng, $lat,$distance = 5) {
        $dlng =  2 * asin(sin($distance / (2 * 6371)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);
        $dlat = $distance/6371;//地球半径，平均半径为6371km
        $dlat = rad2deg($dlat);
        return array(
            'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
            'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
            'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
            'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
        );
    }

    /**
     * 社区列表
     */
    public function getCommunityList()
    {
        $param = $this->request->param();
        $where = ' status = 0 and open_dynamic=1 ';
        $sear['pagesize'] = isset( $param['pagesize'] ) ? $param [ 'pagesize' ] : $this->pageNum;

        $type = 1;
        if(!empty($param['type'])){
            $type = $param['type'];//关注:1   推荐:2  最新:3  附近:4
        }


        $order = 'id desc';
        $map = [];
        if($type == 1){
            $be_uid = '';
            if(!empty($param['userid'])){
                $follow_list = db('community_follow')->where('userid',$param['userid'])->select();
                foreach ($follow_list as $items){
                    if(!empty($be_uid)){
                        $be_uid .= ',';
                    }
                    $be_uid .= "'".$items['be_uid']."'";
                }
            }
            if(!empty($be_uid)){
                $where .=" and userid in (".$be_uid.") ";
            }else{
                $where .=" and userid = -1";
            }
        }elseif($type == 2){
            $order = ' likes DESC';
        }elseif($type == 3){
            $order = ' addtime DESC';
        }elseif($type == 4){
            if(!empty($param['lat']) && $param['lat']>0 && !empty($param['lng']) && $param['lng']>0){
                $latitude=$param['lat'];
                $longitude=$param['lng'];
                $array = $this->returnSquarePoint($longitude, $latitude);
                $map = array(
                    'lat' => array(array('EGT',$array['right-bottom']['lat']),array('ELT',$array['left-top']['lat']),'and'),
                    'lng' => array(array('EGT',$array['left-top']['lng']),array('ELT',$array['right-bottom']['lng']),'and'),
                );
            }
        }

        if(!empty($param['content'])){
            $where .=" and content like %'".$param['content']."'% ";
        }
        if(!empty($param['catid'])){
            $where .=' and catid = '.$param['catid'];
        }

        $list = db('community')->where($where)->where($map)->order($order)->paginates($sear['pagesize'] )->each(function ($item) use ($param) {
            $is_like = false;
            if(!empty($param['userid'])){
                //是否点赞
                $likes_count = db('community_likes')->where('userid',$param['userid'])->where('community_id',$item['id'])->count();
                if($likes_count>0){
                    $is_like = true;
                }
            }
            $item['is_like'] = $is_like;
            //评论列表
            $comment_list = db('community_comment')->where('pid',0)->where('community_id',$item['id'])->order('id desc')->limit(3)->select()->each(function ($comment_item){

                $res = $this->getTree($comment_item['id']);
                if(!empty($res) && sizeof($res)>0){
                    $comment_item['children'] = $res;
                }

                $member_info = Db::name('member')->where('uid',$comment_item['userid'])->find();
                $comment_item['nick_name'] = $member_info['nick_name'];
                $comment_item['addtime'] = date('Y-m-d H:i:s',$comment_item['addtime']);

                $member_info_two = Db::name('member')->where('uid',$comment_item['touserid'])->find();
                $to_nick_name = '';
                if(!empty($member_info_two)){
                    $to_nick_name = $member_info_two['nick_name'];
                }
                $comment_item['to_nick_name'] = $to_nick_name;

                return $comment_item;
            });


            $item['comment_list'] = $comment_list;

            //分类名称
            $category_name = '';
            $category = db('community_category')->where('id',$item['catid'])->find();
            if(!empty($category)){
                $category_name = $category['title'];
            }
            $item['category_name'] = $category_name;
            //是否关注
            $is_follow = false;
            if(!empty($param['userid'])){
                $follow_count = db('community_follow')->where('userid',$param['userid'])->where('be_uid',$item['userid'])->count();
                if($follow_count>0){
                    $is_follow = true;
                }
            }

            $item['is_follow'] = $is_follow;

            if(!empty($item['img'])){
                $pieces = explode(",", $item['img']);
                $img_list = array();
                foreach ($pieces as $items){
                    array_push($img_list,ZY_APP_PATH.$items);
                }
                $item['img'] = $img_list;
            }
            //用户详情
            $userInfo = db('member')->where('uid',$item['userid'])->find();
            if(!empty($userInfo)){
                $userInfo['head_portrait'] = ZY_APP_PATH.$userInfo['head_portrait'];
            }
            $item['user_info'] = $userInfo;
            $distance = '0';//距离
            //获取距离
            if(!empty($item['lng']) && !empty($item['lat']) && !empty($param['lng']) && !empty($param['lat'])){
                $distance = $this->GetDistance($item['lat'],$item['lng'],$param['lat'],$param['lng']);
            }
            $item['distance'] = $distance;

            //获取城市名称


            return $item;
        });

        $new_list = $list->toArray();
        if($type == 4){
            usort($new_list['data'], function($a, $b) {
                return $a["distance"] - $b["distance"];
            });
        }

        return api_json_echo( true , '获取成功' , $new_list , 200);
    }

    //经纬度转城市名称(返回城市id,城市名称)
    //$ak开发密钥,$lat纬度,$lng经度,$type返回数据类型
    public function getCityName($lat,$lng)
    {
        $ak = 'BqBV6EyadsBwrU24B3UF0W8Dp8HuyThX';
        $callback=array('cityCode'=>0,'cityName'=>'');
        $apiUrl='http://api.map.baidu.com/reverse_geocoding/v3/?ak='.$ak.'&output=json&coordtype=wgs84ll&location='.$lat.','.$lng;
        $ret=json_decode(file_get_contents($apiUrl),true);

        if($ret['status']==0){
            $callback['cityCode']=$ret['result']['cityCode'];
            $callback['cityName']=$ret['result']['addressComponent']['city'];

        }
        return $callback['cityName'];
    }


    /**
     * 计算两组经纬度坐标 之间的距离
     * params ：lat1 纬度1； lng1 经度1； lat2 纬度2； lng2 经度2； len_type （1:m or 2:km);
     * return m or km
     */
    public function GetDistance($lat1, $lng1, $lat2, $lng2, $len_type = 2, $decimal = 2)
    {
        defined('EARTH_RADIUS') || define('EARTH_RADIUS', 6378.137); // 地球半径
        defined('PI') || define('PI', 3.1415926);
        $radLat1 = $lat1 * PI / 180.0;
        $radLat2 = $lat2 * PI / 180.0;
        $a       = $radLat1 - $radLat2;
        $b       = ($lng1 * PI / 180.0) - ($lng2 * PI / 180.0);
        $s       = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s       = $s * EARTH_RADIUS;
        $s       = round($s * 1000);
        if ($len_type > 1) {
            $s /= 1000;
        }
        return round($s, $decimal);
    }

    /**
     * 评论列表和社区详情
    */
    public function commentList(){
        $param = $this->request->param();
        if(empty($param['community_id'])){
            return api_json_echo(false, '未获取到community_id！', null, 101);
        }
        $community_id = $param['community_id'];//社区文章id
        $order = 'id desc';

        $list = db('community_comment')->where('pid',0)->where('community_id',$community_id)->order($order)->select()->each(function ($item){
            $member_info = Db::name('member')->where('uid',$item['userid'])->find();
            $item['nick_name'] = $member_info['nick_name'];
            $item['head_portrait'] = ZY_APP_PATH.$member_info['head_portrait'];
            $item['addtime'] = date('Y-m-d H:i:s',$item['addtime']);

            $member_info_two = Db::name('member')->where('uid',$item['touserid'])->find();
            $to_nick_name = '';
            if(!empty($member_info_two)){
                $to_nick_name = $member_info_two['nick_name'];
            }
            $item['to_nick_name'] = $to_nick_name;


            $res = $this->getTree($item['id']);
            if(!empty($res) && sizeof($res)>0){
                $item['children'] = $res;
            }
            return $item;
        });
        //详情
        $info = db('community')->where('id',$community_id)->find();
        if(!empty($info['img'])){
            $pieces = explode(",", $info['img']);
            $img_list = array();
            foreach ($pieces as $item){
                array_push($img_list,ZY_APP_PATH.$item);
            }
            $info['img'] = $img_list;
        }

        $is_like = false;
        if(!empty($param['userid'])){
            //是否点赞
            $likes_count = db('community_likes')->where('userid',$param['userid'])->where('community_id',$community_id)->count();
            if($likes_count>0){
                $is_like = true;
            }
        }
        $info['is_like'] = $is_like;

        db('community')->where('id',$community_id)->setInc('view_num');

        $result = [
            'comment_list'=>$list,
            'info'=>$info
        ];

        return api_json_echo( true , '获取成功' , $result , 200);
    }

    //获取所有上级树
    public function getTree($id){
        return db('community_comment')->where('pid',$id)->select()->each(function ($items){

            $member_info = Db::name('member')->where('uid',$items['userid'])->find();
            $items['nick_name'] = $member_info['nick_name'];
            $items['addtime'] = date('Y-m-d H:i:s',$items['addtime']);

            $member_info_two = Db::name('member')->where('uid',$items['touserid'])->find();
            $to_nick_name = '';
            if(!empty($member_info_two)){
                $to_nick_name = $member_info_two['nick_name'];
            }
            $items['to_nick_name'] = $to_nick_name;

            $res = self::getTree($items['id']);
            if(!empty($res) && sizeof($res)>0){
                $items['children'] = $res;
            }
            return $items;
        });
    }


    /**
     * 发布社区评论
     * @throws Exception
     */
    public function publicComment(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $add_data['addtime'] = time();
        $add_data['userid'] = $param['userid'];
        if(!empty($param['community_id'])){
            $add_data['community_id'] = $param['community_id'];
        }
        if(!empty($param['pid'])){
            $add_data['pid'] = $param['pid'];
        }
        if(!empty($param['content'])){
            $add_data['content'] = $param['content'];
        }
        if(!empty($param['img'])){
            $add_data['img'] = $param['img'];
        }
        if(!empty($param['touserid'])){
            $add_data['touserid'] = $param['touserid'];
        }
        $res = db('community_comment')->insert($add_data);
        if($res){
            //社区表字段加一
            db('community')->where('id',$param['community_id'])->setInc('comment',1);
            return api_json_echo( true , '发布成功' , '发布成功' , 200);
        }
        return api_json_echo( false , '发布失败' , '发布失败' , 300);

    }

    /**
     * 社区点赞/取消点赞
     * @throws Exception
     */
    public function communityLikes(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['community_id'])){
            return api_json_echo(false, '未获取到community_id！', null, 101);
        }
        $info = db('community_likes')->where('userid',$param['userid'])->where('community_id',$param['community_id'])->find();
        if(empty($info)){
            $add_data['userid'] = $param['userid'];
            $add_data['community_id'] = $param['community_id'];
            $add_data['addtime'] = time();
            $res = db('community_likes')->insert($add_data);
            if($res){
                //社区表字段加一
                db('community')->where('id',$param['community_id'])->setInc('likes',1);
                return api_json_echo( true , '点赞成功' , '点赞成功' , 200);
            }
        }else{
            $res = db('community_likes')->where('id',$info['id'])->delete();
            if($res){
                //社区表字段减一
                db('community')->where('id',$param['community_id'])->setDec('likes',1);
                return api_json_echo( true , '取消点赞成功' , '取消点赞成功' , 200);
            }
        }
        return api_json_echo( false , '操作失败' , '操作失败' , 300);
    }

    /**
     * 用户举报
     */
    public function communityReport(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['community_id'])){
            return api_json_echo(false, '未获取到community_id！', null, 101);
        }
        if(!empty($param['content'])){
            $add_data['content'] = $param['content'];
        }
        $add_data['userid'] = $param['userid'];
        $add_data['community_id'] = $param['community_id'];
        $add_data['addtime'] = time();

        $info = db('community_report')->where('community_id',$param['community_id'])->where('userid',$param['userid'])->find();
        if(!empty($info)){
            return api_json_echo( true , '您已举报过,请勿重复操作!' , '您已举报过,请勿重复操作!' , 200);
        }

        $res = db('community_report')->insert($add_data);
        if($res){
            return api_json_echo( true , '举报成功' , '举报成功' , 200);
        }
        return api_json_echo( false , '举报失败' , '举报失败' , 300);
    }

    /**
     * 关注/取消关注
     * @throws Exception
     */
    public function communityFollow(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['be_uid'])){
            return api_json_echo(false, '未获取到be_uid！', null, 101);
        }
        if($param['userid'] == $param['be_uid']){
            return api_json_echo(false, '无法关注本人！', '无法关注本人！', 101);
        }
        $info = db('community_follow')->where('userid',$param['userid'])->where('be_uid',$param['be_uid'])->find();
        if(empty($info)){
            $add_data['userid'] = $param['userid'];
            $add_data['be_uid'] = $param['be_uid'];
            $add_data['addtime'] = time();
            $res = db('community_follow')->insert($add_data);
            if($res){
                return api_json_echo( true , '关注成功' , '关注成功' , 200);
            }
        }else{
            $res = db('community_follow')->where('id',$info['id'])->delete();
            if($res){
                return api_json_echo( true , '取消关注成功' , '取消关注成功' , 200);
            }
        }
        return api_json_echo( false , '操作失败' , '操作失败' , 300);
    }

    /**
     * 是否黑名单
     * @throws Exception
     */
    public function userBlack(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['check_userid'])){
            return api_json_echo(false, '未获取到check_userid！', null, 101);
        }

        //判断是否已加入黑名单
        $is_black = false;
        $is_add = db('friend_blacklist')->where('userid',$param['userid'])->where('beuserid',$param['check_userid'])->count();
        if($is_add>0){
            $is_black = true;
        }

        return api_json_echo( true , '查询成功' , $is_black , 200);
    }

    /**
	 * 个人展示
     * @throws Exception
	 */
    public function userCommunity(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        if(empty($param['check_userid'])){
            return api_json_echo(false, '未获取到check_userid！', null, 101);
        }
        $sear['pagesize'] = isset( $param['pagesize'] ) ? $param [ 'pagesize' ] : $this->pageNum;

        $community_list = db('community')->where('userid',$param['check_userid'])->where('status',0)->paginates($sear['pagesize'] )->each(function ($item){
            if(!empty($item['img'])){
                $img_list = array();
                $pieces = explode(",", $item['img']);
                foreach ($pieces as $items){
                    array_push($img_list,ZY_APP_PATH.$items);
                }
                $item['img'] = $img_list;
            }
            return $item;
        });

        $member = db('member')->where('uid',$param['check_userid'])->find();
        if(!empty($member)){
            $member['head_portrait'] = ZY_APP_PATH.$member['head_portrait'];
            if(!empty($member['bg_img'])){
                $member['bg_img'] = ZY_APP_PATH.$member['bg_img'];
            }
            //未公开动态,查询为空
            if($param['userid'] != $param['check_userid']){
                if( $member['open_dynamic'] == 0){
                    $community_list = [];
                }
            }
        }
        //判断是否已加入黑名单
        $is_black = false;
        $is_add = db('friend_blacklist')->where('userid',$param['userid'])->where('beuserid',$param['check_userid'])->count();
        if($is_add>0){
            $is_black = true;
        }

        $is_follow = false;
        $follow_info = db('community_follow')->where('userid',$param['userid'])->where('be_uid',$param['check_userid'])->find();
        if(!empty($follow_info)){
            $is_follow = true;
        }

        $res=[
            'community_list'=>$community_list,//社区列表
            'member'=>$member,//用户信息
            'isFollow'=>$is_follow,//是否关注
            'is_black'=>$is_black,//是否黑名单
        ];

        return api_json_echo( true , '查询成功' , $res , 200);
    }


    /**
     * 上传图片
     */
    public function upload()
    {
        $data        = $this->request->param();
        $file        = $_FILES['file'];
        $upload_path = "/upload/images";
        $res = uploadImg($file, $upload_path);
        if ($res['status'] != true) {
            return api_json_echo(false, '上传失败', $res['message'], $res['code']);
        }
        return api_json_echo(true, '上传成功', $res['data'], 200);
    }


    public function upload_base(){
        $param  = $this->request->param();
        $base64_image_content = $param['img'];
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            //图片后缀
            $type = $result[2];
            //保存位置--图片名
            $image_name=date('His').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).".".$type;
            $image_file_path = '/upload/'.date('Ymd');
            $image_file = ROOT_PATH.'public'.$image_file_path;
            $imge_real_url = $image_file.'/'.$image_name;
            $imge_web_url = $image_file_path.'/'.$image_name;
            if (!file_exists($image_file)){
                mkdir($image_file, 0700);
                fopen($image_file.'\\'.$image_name, "w");
            }
            //解码
            $decode=base64_decode(str_replace($result[1], '', $base64_image_content));

            if (file_put_contents($imge_real_url, $decode)){
                $url=ZY_APP_PATH.$imge_web_url;
            }else{
                $url='';
            }
        }else{
            $url='';
        }
        return api_json_echo(true, '上传成功', $url, 200);
    }



}